/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Server.DAO;

import Server.DTO.DataBaseInfo;

import java.util.logging.Level;
import java.util.logging.Logger;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;


/**
 *
 * @author Trung
 */
public class DatabaseInfoDAO {
    private Document document = null;
    
    /** Creates new optionDAO */
    public DatabaseInfoDAO(){
        DocumentBuilder builder = null;
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        
        try {
            builder = factory.newDocumentBuilder();
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(DatabaseInfoDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        document = builder.newDocument();
        
    }
    
    ///Write config to xml file
    public void writeConfig(DataBaseInfo configDTO, String path) throws ParserConfigurationException{
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document dcmt = builder.newDocument();
        
        Element root = (Element) dcmt.createElement("Config");        
            
        root.setAttribute("username", configDTO.getUsername());
        root.setAttribute("password", configDTO.getPassword());
        root.setAttribute("check", configDTO.getCheck());
        root.setAttribute("workspace", configDTO.getWorkspace());
        
        dcmt.appendChild(root);
        // Normalizing the DOM
        dcmt.getDocumentElement().normalize();
        
        DocumentUlti.writeDocToFile(path, dcmt); 
    }
    
    ///Read config file
    public DataBaseInfo readConfigFile(String path){
        DataBaseInfo config = new DataBaseInfo();
        
        document = DocumentUlti.parse(path);
        
        Element root = document.getDocumentElement();
        
        config.setUsername(root.getAttribute("username"));
        config.setPassword(root.getAttribute("password"));
        config.setCheck(root.getAttribute("check"));
        config.setWorkspace(root.getAttribute("workspace"));        
        
        return config;
    }
}
